<template>
  <div>
    <h4>3. 确认货件单混装箱商品信息</h4>
    <div class="font-red f14 mgb10">
      移仓入库的商品，需确认有多少个货件箱和货箱信息。请通过下方列表的添加货件箱按钮确认箱子数量和每箱存放的商品数量、箱唛、物流信息，多个货件箱请多次添加
    </div>
    <div class="f14 mgb10">
      <div style="display: inline-block" class="mgr10">待确认商品数量：<span class="font-red">{{waitConfirmNum}}</span></div>
      <div style="display: inline-block">已确认商品数量：<span class="font-red">{{confirmNum}}</span></div>
    </div>
    <div class="goods-table">
      <el-table
        border
        :data="showTableData"
        :span-method="objectSpanMethod2"
      >
        <el-table-column
          prop="oldBoxId"
          label="旧箱唛"
          align="center"
          min-width="120"
        >
          <template v-slot="{row}">
            <template v-if="row.editStatus">
              <el-input
                v-model="row.oldBoxId"
                placeholder="请输入"
                :id="`${row.id}editOldBoxId`"
                @blur="row.editStatus = false;"
              ></el-input>
            </template>
            <template v-else>
              <span>
                {{ row.oldBoxId }}
              </span>
              <i class="el-icon-edit mgl10" style="cursor: pointer" @click="editOldBoxId(row)"></i>

            </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="boxType"
          label="货箱类型"
          min-width="100"
          align="center"
        >
          <template v-slot="{row}">
            {{getBoxTypeStr(row.boxType)}}
          </template>
        </el-table-column>
        <template v-if="plan.haveLogisticsNo">
          <el-table-column
            label="物流单号"
            prop="logisticsNo"
            align="center"
            min-width="120"
            show-overflow-tooltip
          >
            <template v-slot="{row}">
              {{row.logisticsNo || '-'}}
            </template>
          </el-table-column>
          <el-table-column
            label="预计送达时间"
            prop="estimateTime"
            align="center"
            width="150"
          >
            <template v-slot="{row}">
              {{row.estimateTime || '-'}}
            </template>
          </el-table-column>
        </template>
        <el-table-column
          :label="$t('table.ListingIDAndSKU')"
          align="left"
          min-width="300"
        >
          <template slot-scope="{row}">
            <template v-if="row.isTB">
              <span class="font-red">
                {{$t('shipment.Not labeled')}} {{row.sku ? `(${row.sku})` : ''}}
              </span>
            </template>
            <template v-else-if="row.isSystem">
              {{ $t('shipment.System label') }} ({{row.sku}})
            </template>
            <template v-else>
              {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
            </template>
          </template>
        </el-table-column>
        <m-l-code-column></m-l-code-column>

        <el-table-column
          label="预计发货数量"
          prop="boxGoodsNum"
          align="left"
          width="200"
        ></el-table-column>
        <el-table-column
          label="货箱商品总数"
          align="left"
          width="200"
          prop="sumBoxNum"
        >
          <template v-slot="{row}">
            {{getSumBoxNum(row)}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          prop="op"
        >
          <template slot-scope="{row}">
            <template>
              <el-button type="primary" @click="editDialog(row)">修改</el-button>
              <el-button type="danger" @click="removeBox(row)" v-if="row.boxType === MIXIN_BOX()">删除</el-button>
            </template>
          </template>
        </el-table-column>

      </el-table>
      <div class="add-mixin-box" @click="addDialog" v-if="waitConfirmNum > 0">
        <i class="el-icon-plus" style="font-weight: bold"></i>
        添加混箱
      </div>
    </div>

    <el-dialog
      :title="currentBoxType === MIXIN_BOX() ? '编辑混箱商品' : '编辑整箱数据'"
      :visible.sync="dialog"
      width="1300px"
    >
      <div>
        <div class="tips mgb10">请选择填写当前货件箱存放的商品数量和其他箱唛信息</div>
        <div>
          <el-form label-width="130px" label-suffix=":">
            <el-form-item label="旧箱唛">
              <el-input v-model="currentDialogForm.oldBoxId"></el-input>
            </el-form-item>
            <template v-if="plan.haveLogisticsNo">
              <el-form-item label="物流单号">
                <el-input v-model="currentDialogForm.logisticsNo"></el-input>
              </el-form-item>
              <el-form-item label="预计送达时间">
                <el-date-picker
                  v-model="currentDialogForm.estimateTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                >
                </el-date-picker>
              </el-form-item>
            </template>

          </el-form>
        </div>

        <el-table
          border
          :data="showDialogGoodsTable"
          :span-method="objectSpanMethod"
          :key="index"
          v-if="currentBoxType === MIXIN_BOX()"
        >
          <el-table-column
            prop="image"
            :label="$t('table.productCover')"
            align="center"
            width="120"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="title"
            :label="$t('table.title')"
            align="left"
            min-width="300"
          >
            <template slot-scope="{row}">
              {{row.title}}
              <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.ListingIDAndSKU')"
            align="left"
            width="300"
          >
            <template slot-scope="{row}">
              <template v-if="row.isTB">
                  <span class="font-red">
                    {{$t('shipment.Not labeled')}} {{row.sku ? `(${row.sku})` : ''}}
                  </span>
              </template>
              <template v-else-if="row.isSystem">
                {{ $t('shipment.System label') }} ({{row.sku}})
              </template>
              <template v-else>
                {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="预计发货数量"
            width="180"
            prop="exGoodsMixinNum"
            align="center"
          ></el-table-column>
          <el-table-column
            label="可编辑数量"
            prop="canEditNum"
            width="150"
            align="center"
          ></el-table-column>

          <el-table-column
            label="数量"
            width="170"
            prop="boxGoodsNum"
            align="center"
          >
            <template v-slot="{row}">
              <el-input-number
                :min="0"
                :max="row.canEditNum"
                :precision="0"
                v-model="row.boxGoodsNum"
                @change="test1"
              ></el-input-number>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="confirmMixinGoods">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import v4 from "uuid/dist/esm-node/v4";
import {deepCopy} from "@/utils";
import {v1} from "uuid";
import {generateRandomString} from "@/utils/common";
import {FULL_BOX, getBoxTypeStr, MIXIN_BOX} from "@/utils/boxLabel";
import {OB} from "caniuse-lite/data/browserVersions";

export default {
  name: 'addShipmentStep3MW',
  components: {MLCodeColumn},
  props: {
    moveWarehouseBoxList: {
      type: Array,
    },
    mixinBoxGoodsList: {
      type: Array,
    },
    chooseWareGoodsMixinList: {
      type: Array,
    },
    mixinBoxArr: {
      type: Array,
    },
    waitConfirmNum: {
      type: Number,
    },
    confirmNum: {
      type: Number,
    },
    plan: {
      type: Object,
    }
  },
  computed: {
    // 只显示可编辑的商品
    showDialogGoodsTable(){
      return this.dialogGoodsTable.filter(item => item.canEditNum > 0)
    },
    showTableData(){
      return [...this.moveWarehouseBoxList, ...this.mixinBoxGoodsList]
    },
  },
  data(){
   return {
     dialog: false,
     dialogGoodsTable: [],
     currentDialogForm: {
       oldBoxId: '',
       logisticsNo: '',
       estimateTime: '',
     },
     currentMixinBox: '', // 当前混箱的序号
     currentBoxType: '',
     index: 1,
   }
  },
  methods: {
    getBoxTypeStr,
    MIXIN_BOX() {
      return MIXIN_BOX
    },
    // 添加混箱
    addDialog(){
      this.index++
      this.dialog = true
      this.currentBoxType = MIXIN_BOX
      this.createMixinBox()
      this.createDialogGoodsTable()
    },
    // 修改混箱
    editDialog(row){
      this.dialog = true
      this.currentMixinBox = row.boxIndex
      this.currentDialogForm.logisticsNo = row.logisticsNo
      this.currentDialogForm.estimateTime = row.estimateTime
      this.currentDialogForm.oldBoxId = row.oldBoxId
      this.currentBoxType = row.boxType
      this.createDialogGoodsTable()
    },
    // 移除箱子
    removeBox(row){
      this.$confirm('','确认删除该箱子吗？')
        .then(res=>{
          const boxIndex = row.boxIndex
          this.mixinBoxArr.splice(this.mixinBoxArr.findIndex(item => item === boxIndex), 1)
          this.removeMixinBoxGoodsListByBoxIndex(boxIndex)
        })
        .catch(res=>{

        })
    },
    // 根据箱子序号移除商品 (mixinBoxGoodsList是props传过来的 不能直接改变该变量的内存地址)
    removeMixinBoxGoodsListByBoxIndex(boxIndex){
      let flag = true
      while (flag){
        const index = this.mixinBoxGoodsList.findIndex(item=> item.boxIndex === boxIndex)
        if(index === -1){
          flag = false
          break;
        }
        this.mixinBoxGoodsList.splice(index, 1)
      }
      this.sortTable()
    },
    // 生成对话框的表格table数据
    createDialogGoodsTable(){
      this.dialogGoodsTable = [];
      this.chooseWareGoodsMixinList.map(item=> {
        item.canEditNum = item.exGoodsMixinNum; // 剩余的数量
        item.boxGoodsNum = 0; // 当前的数量

        // 找到对应的箱子上的商品数量
        const mixinGoodsRow = this.mixinBoxGoodsList.find(_item=> _item.id === item.id && _item.boxIndex === this.currentMixinBox)
        if(mixinGoodsRow){
          item.boxGoodsNum = mixinGoodsRow.boxGoodsNum
        }

        // 可编辑数量 = 总数量 - 其他箱子商品数量总和
        const goods = this.mixinBoxGoodsList.filter(_item => _item.id === item.id && _item.boxIndex !== this.currentMixinBox)
          .reduce((prev, curr) => {
            return prev + curr.boxGoodsNum
          }, 0)
        item.canEditNum = item.exGoodsMixinNum - goods
        this.dialogGoodsTable.push(deepCopy(item))
        return item
      })
    },
    // 生成唯一的箱子序号 (随机字符串)
    createMixinBox(){
      this.currentMixinBox = generateRandomString()
      this.currentDialogForm.logisticsNo = ''
      this.currentDialogForm.estimateTime = ''
      this.currentDialogForm.oldBoxId = ''
    },
    // 获取箱子的箱子序号 （1,2,3）
    getMixinBoxIndex(row){
      const index = this.mixinBoxArr.findIndex(item=> row.boxIndex === item)
      return index + 1
    },
    // 确认
    confirmMixinGoods(){
      if(this.currentBoxType === FULL_BOX){
        const row = this.moveWarehouseBoxList.find(item => item.boxIndex === this.currentMixinBox)
        row.logisticsNo = this.currentDialogForm.logisticsNo;
        row.estimateTime = this.currentDialogForm.estimateTime;
        row.oldBoxId = this.currentDialogForm.oldBoxId;
        this.$forceUpdate()
        this.dialog = false
        return;
      }
      this.dialog = false
      const filterGoods = this.dialogGoodsTable.filter(item=> item.boxGoodsNum > 0);
      // 移除
      let index = this.mixinBoxArr.findIndex(item => item === this.currentMixinBox)
      if(filterGoods.length === 0){
        this.mixinBoxArr.splice(index, 1)
      }else{
        if(index === -1){
          this.mixinBoxArr.push(this.currentMixinBox)
        }
      }
      this.removeMixinBoxGoodsListByBoxIndex(this.currentMixinBox)

      filterGoods.map(item=>{
        item.boxIndex = this.currentMixinBox
        item.boxType = 'mixin_box'
        item.editStatus = false
        item.logisticsNo = this.currentDialogForm.logisticsNo;
        item.estimateTime = this.currentDialogForm.estimateTime;
        item.oldBoxId = this.currentDialogForm.oldBoxId;
        this.mixinBoxGoodsList.push(deepCopy(item))
        return item;
      })
      this.sortTable()
    },
    sortTable(){
      this.mixinBoxGoodsList.sort((a,b)=>{
        return this.getMixinBoxIndex(a) - this.getMixinBoxIndex(b)
      })
    },
    // 计算这个箱子总共的商品数量
    getSumBoxNum(row){
      return this.showTableData.filter(item=> item.boxIndex === row.boxIndex)
        .reduce((prev,curr)=>{
          return prev + curr.boxGoodsNum
        },0)
    },
    test1(){
      // console.log(this.dialogGoodsTable)
    },
    // dialog单元格合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }){
      const mergeCell = this.getMergeCell(this.dialogGoodsTable)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    getMergeCell(list){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      list.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并


        if(item.suitId && item.suitId === list[index - 1].suitId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },

    // 表单单元格合并
    objectSpanMethod2({ row, column, rowIndex, columnIndex }){
      const mergeCell = this.getMergeCell2(this.showTableData)
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    getMergeCell2(list){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'boxIndex',
        'sumBoxNum',
        'op',
        'oldBoxId',
        'boxType',
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      list.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并


        if(item.boxIndex && item.boxIndex === list[index - 1].boxIndex){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    editOldBoxId(row){
      row.editStatus = true;
      this.$nextTick(()=>{
        document.getElementById(`${row.id}editOldBoxId`).focus()
      })
    }

  }
}

</script>

<style scoped lang="scss">
.add-mixin-box{
  border: #dfe6ec 1px solid;
  padding: 10px;
  font-size: 14px;
  cursor: pointer;
  text-align: center;
  color: rgb(64, 158, 255);
  font-weight: bold;
}
</style>
